from rest_framework_simplejwt.authentication import JWTAuthentication
from django.core.cache import cache
from rest_framework_simplejwt.tokens import RefreshToken
from django.core.cache import cache
from rest_framework_simplejwt.settings import api_settings

class MyJWTAuthentication(JWTAuthentication):
    def authenticate(self, request):
        # print('start auth.............................')
        header = self.get_header(request)
        if header is None:
            # print("no header")
            return None

        raw_token = self.get_raw_token(header)
        if raw_token is None:
            # print("no atoken")
            return None
        
        access_token = raw_token.decode()
        if cache.get(access_token) is None:
            key_refresh = f'{access_token}:refresh'
            refresh_token = cache.get(key_refresh)
            if refresh_token is None:
                # print(f'<{key_refresh}> has no rtoken')
                return None
            # access expires but refresh not expire, delete expired key and set new key in cache
            # print('getting new access token.............................')
            # import pdb;pdb.set_trace()
            refresh = RefreshToken(refresh_token)
            raw_token = str(refresh.access_token)
            access_token = raw_token
            cache.set(access_token, '',
                  timeout=api_settings.ACCESS_TOKEN_LIFETIME.total_seconds())
            # 新的rtoken的timeout应该设置为之前的rtoken的ttl
            ttl = cache.ttl(key_refresh)
            cache.set(f'{raw_token}:refresh', refresh_token, timeout=ttl)
            cache.delete(key_refresh)
            
        validated_token = self.get_validated_token(raw_token)
        user = self.get_user(validated_token)
        # import pdb;pdb.set_trace()
        cache.set(f"{user.id}:access_token", access_token, timeout=api_settings.ACCESS_TOKEN_LIFETIME.total_seconds())
        # print("before return ", user, validated_token)
        return user, validated_token
